<template>
  <OrderPreSkeleton v-if="loading"></OrderPreSkeleton>
  <view v-else class="viewport">
    <view class="content">
      <navigator url="/pagesMember/address/address" class="address-box" hover-class="none">
        <view v-if="selectedAddress">
          <view class="user-box">
            <view class="user">{{ selectedAddress.receiver }}</view>
            <view class="contact">{{ selectedAddress.contact }}</view>
          </view>
          <view class="address"
            >{{ selectedAddress.fullLocation }} {{ selectedAddress.address }}</view
          >
        </view>
        <view class="tip" v-else>请选择收获地址</view>
      </navigator>

      <view class="goods-box">
        <navigator
          :url="`/pages/goods/goods?id=${item.id}`"
          v-for="item in goods"
          :key="item.id"
          hover-class="none"
        >
          <view class="good">
            <view class="image">
              <image class="pic" :src="item.picture" mode="aspectFill"></image>
            </view>
            <view class="meta">
              <view class="name">{{ item.name }}</view>
              <text class="attrs">{{ item.attrsText }}</text>
              <view class="price-count">
                <view class="price">
                  <view class="price-pay symbol">{{ item.totalPayPrice }}</view>
                  <view class="price-old symbol">{{ item.totalPrice }}</view>
                </view>
                <view class="count"> x{{ item.count }}</view>
              </view>
            </view>
          </view>
        </navigator>
      </view>

      <view class="info">
        <view class="delivery common-item">
          <text class="label">配送时间</text>
          <picker
            class="value"
            mode="selector"
            :range="deliveryList"
            range-key="text"
            @change="onChangeDelivery"
          >
            <view class="icon-fonts picker">{{ activeDelivery.text }}</view>
          </picker>
        </view>
        <view class="notes common-item">
          <text class="label">订单备注</text>
          <input
            v-model="orderNotes"
            class="input value"
            type="text"
            placeholder="选题，建议留言前与商家沟通确认"
          />
        </view>
      </view>

      <view class="price-info">
        <view class="common-item">
          <text class="label">商品总价</text>
          <text class="value symbol">{{ summary?.totalPrice }}</text>
        </view>
        <view class="common-item">
          <text class="label">运费</text>
          <text class="value symbol">{{ summary?.postFee }} </text>
        </view>
      </view>
    </view>

    <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
      <view class="total-price">{{ summary?.totalPayPrice }}</view>
      <button class="to-pay" :disabled="!selectedAddress" @tap="onPostOrder">提交订单</button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app'
import Api from '@/services'
import type { TOrderGood, TOrderPre, TOrderSummary, TOrderUserAddress } from '@/types/order'
import { computed, ref } from 'vue'
import { useAddressStore } from '@/stores/modules/address'
import OrderPreSkeleton from './components/OrderPreSkeleton.vue'

const addresses = ref<TOrderUserAddress[]>()
const summary = ref<TOrderSummary>()
const goods = ref<TOrderGood[]>([])
const orderNotes = ref('') //订单备注
const loading = ref(true)
// 配送时间
const deliveryList = ref([
  { type: 1, text: '时间不限（周一至周日）' },
  { type: 2, text: '工作日送（周一至周五）' },
  { type: 3, text: '周末配送（周六至周日）' },
])
// 配送下标
const activeIndex = ref(0)
const addressStore = useAddressStore()

// 获取安全距离
const { safeAreaInsets } = uni.getSystemInfoSync()

const selectedAddress = computed(() => {
  console.log('computed')
  return addressStore.selectedAddress || addresses.value?.find((i) => i.isDefault)
})

// 当前配送时间
const activeDelivery = computed(() => {
  return deliveryList.value[activeIndex.value]
})

const getPreData = async (flag?: string, ...args: string[]) => {
  let result: TOrderPre

  if (flag === 'now') {
    const { result: result_2 } = await Api.OrderAPI.getOrderPreDetailNow({
      skuId: args[0],
      count: args[1],
    })
    result = result_2
  } else if (flag === 'repurchase') {
    const { result: result_3 } = await Api.OrderAPI.getOrderRepurchaseById(args[0])
    result = result_3
  } else {
    const { result: result_4 } = await Api.OrderAPI.getOrderPreDetail()
    result = result_4
  }
  addresses.value = result.userAddresses
  summary.value = result.summary
  goods.value = result.goods
}

onLoad(async (options) => {
  loading.value = true
  const skuId = options?.skuId
  const count = options?.count
  const orderId = options?.orderId
  if (skuId && count) {
    await getPreData('now', skuId, count)
  } else if (orderId) {
    await getPreData('repurchase', orderId)
  } else {
    await getPreData()
  }
  loading.value = false
})

// 修改配送时间
const onChangeDelivery: UniHelper.SelectorPickerOnChange = (ev) => {
  activeIndex.value = ev.detail.value
}

const onPostOrder = async () => {
  const _goods = goods.value.map((i) => {
    return {
      skuId: i.skuId,
      count: i.count,
    }
  })
  const params = {
    goods: _goods,
    addressId: selectedAddress.value?.id,
    deliveryTimeType: activeDelivery.value.type,
    buyerMessage: orderNotes.value,
    payType: 1,
    payChannel: 2,
  }

  const { result } = await Api.OrderAPI.postOrder(params)
  if (result) {
    uni.redirectTo({
      url: `/pagesOrder/orderDetail/orderDetail?id=${result.id}`,
    })
  }
}
</script>

<style lang="scss" scoped>
@import './styles/orderPre';
</style>
